import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mime_type/mime_type.dart';
import 'package:proj_sfv/component/LoadingOverlay.dart';
import 'package:proj_sfv/domain/Profile.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/store/MyArguments.dart';
import 'package:proj_sfv/utils/Utils.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

class UserProfilePage extends StatefulWidget {
  @override
  _UserProfilePageState createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> {
  String _avatarUrl;
  List<Profile> _avatarUrls = [];
  MyArguments _args;
  bool _loading = false;

  @override
  void didChangeDependencies() {
    _args = ModalRoute.of(context).settings.arguments as MyArguments;
    _loadAvatarUrls();
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  void _loadAvatarUrls() async {
    var resp = await getHistoryProfileRequest(context, _args.id, _args.token);
    if (resp != null) {
      setState(() {
        _avatarUrls = resp;
        _avatarUrl = Uri.https(cosHost, '${_avatarUrls[0].id}.jpg').toString();
      });
    }
  }

  void _pickImage() async {
    final pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      File imageFile = File(pickedFile.path);
      String mimeType = mime(imageFile.path);
      String data = base64Encode(imageFile.readAsBytesSync());
      String base64 = 'data:$mimeType;base64,$data';
      String id = await updateProfileRequest(context, _args.id, _args.token, base64);
      var newImageUrl = Uri.https(cosHost, "$id.jpg").toString();
      // 修改聊天界面头像
      await TencentImSDKPlugin.v2TIMManager.setSelfInfo(userFullInfo: V2TimUserFullInfo(faceUrl: newImageUrl));
      setState(() {
        _avatarUrl = newImageUrl;
        _avatarUrls.insert(0, Profile(id, _args.id, DateTime.now()));
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('用户头像'),
      ),
      body: LoadingOverlay(
        isLoading: _loading,
        child: Column(
          children: [
            SizedBox(height: 32.0),
            CircleAvatar(
              radius: 64.0,
              backgroundImage: _avatarUrl != null ? NetworkImage(_avatarUrl) : null,
              child: _avatarUrl == null ? Icon(Icons.person, size: 64.0) : null,
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('上传头像'),
            ),
            SizedBox(height: 16.0),
            Expanded(
              child: ListView.builder(
                itemCount: _avatarUrls.length,
                itemBuilder: (context, index) {
                  Profile p = _avatarUrls[index];
                  String avatarUrl = Uri.https(cosHost, '${_avatarUrls[index].id}.jpg').toString();
                  return ListTile(
                    leading: CircleAvatar(backgroundImage: NetworkImage(avatarUrl)),
                    title: Text('Avatar ${index + 1}'),
                    onTap: () async {
                      setState(() {
                        _loading = true;
                      });
                      String result = await updateProfileHistoricalRequest(context, _args.id, _args.token, p.id);
                      if (result == null) {
                        // ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("修改失败！")));
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("修改成功")));
                        TencentImSDKPlugin.v2TIMManager.
                          setSelfInfo(userFullInfo: V2TimUserFullInfo(faceUrl: avatarUrl));
                        setState(() {
                          _loading = false;
                          _avatarUrl = avatarUrl;
                        });
                      }

                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

}
